#pragma once
#include <iostream>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"

using namespace LogModule;
const std::string defaultdict = "./dict.txt";
const std::string separator = ": ";

class Dict
{
public:
    Dict(const std::string &dictpath = defaultdict):_dict_path(dictpath)
    {
    }
    void Load()
    {
        // 只读方式打开文件
        std::ifstream ifs(defaultdict);
        if (!ifs.is_open())
        {
            LOG(LogLevel::FATAL) << "open " << defaultdict << " failure!";
            exit(1);
        }
        // data的内容： apple: 苹果
        std::string data;
        while (std::getline(ifs, data))
        {
            size_t pos = data.find(separator);
            // 没找到分割符
            if (pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "加载失败，内容是：" << data;
                continue;
            }
            std::string english = data.substr(0, pos);
            std::string chinese = data.substr(pos + separator.size());
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "加载失败，缺失中文/英文，内容是：" << data;
                continue;
            }
            LOG(LogLevel::INFO) << "加载成功，单词为：" << data;
            _dict.insert(std::make_pair(english, chinese));
        }
        ifs.close();
    }
    std::string Translate(const std::string &english)
    {
        auto it = _dict.find(english);
        if (it == _dict.end())
        {
            LOG(LogLevel::INFO) << "没有找到单词，英文为：" << english;
            return "NONE";
        }
        LOG(LogLevel::INFO) << "找到了对应的单词， " << english << separator << it->second;
        return it->second;
    }
    ~Dict()
    {
    }

private:
    std::string _dict_path; //路径+文件名
    std::unordered_map<std::string, std::string> _dict;
};